/**
 *  编辑页
 *
 * 作者 admin
 * 日期 2024-08-07 16:43:01
 */
layui.extend({
        // tableEdit: 'lay/extends/tableEdit'
    }).use(['jquery','febs', 'form', 'validate','table','upload','fileUpload','autocomplete'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        laydate = layui.laydate,
        form = layui.form,
        table = layui.table,
        commonJS = layui.commonJS,
        fileUpload = layui.fileUpload,
        autocomplete = layui.autocomplete,
        $view = $('#reportSurveyRecord-edit'),
        $obligationDeptName = $('#obligationDeptName'),
        $addInjuryUser = $('#addInjuryUser'),
        $addCulpritUser = $('#addCulpritUser'),
        $addTimeline = $('#addTimeline'),
        validate = layui.validate,
        $accidentCategory = $view.find('#accidentCategory'),
        $accidentType = $view.find('#accidentType'),
        $accidentReason = $view.find('#accidentReason'),
        $accidentLevel = $view.find('#accidentLevel'),
        $emergencyLevel = $view.find('#emergencyLevel'),
        $directReason = $view.find('#directReason'),
        $indirectionReason = $view.find('#indirectionReason'),
        $rootReason = $view.find('#rootReason'),
        $accidentNature = $view.find('#accidentNature'),
        $violationSurvivalRules = $view.find('#violationSurvivalRules'),
        $addOpinion = $view.find("#addOpinion"),
        panelAddReason = 0,
        injuryUserTableIns,
        culpritUserTableIns,
        timelineTableIns,
        tableIns;
    let tenantId = POPUP_DATA.tenantId;
    let reportId = POPUP_DATA.reportId;
    let reportRectificationId = POPUP_DATA.reportRectificationId;
    let injuryUserTableData = [];
    let culpritUserTableData = [];
    let timelineTableData = [];
    let deleteReportRectificationIds = [];
    let surveyAuditRecordList=[];
    let rectificationUsers=[];


    form.verify(validate);
    initDictItemSelect_surveyRecord();
    form.render();
    initFormValue();
    initInjuryUserTable();
    initCulpritUserTable();
    initTimelineTable();

    form.verify({
        obligationRatio: function(value, item){
            if(!commonJS.isEmpty(value)){
                if(!new RegExp(/^(\d|[1-9]\d|100)(\.\d{1,2})?$/).test(value)){
                    return '请输入0到100的整数或两位小数';
                }
            }
        },
    });
    laydate.render({
        elem: "#surveyDate",
        done: function (value, date) {},
        type: 'datetime'
    })

    laydate.render({
        elem: "#rectificationDeadline0",
        done: function (value, date) {},
        type: 'date'
    })

    initSurveyAuditTable();
    function initSurveyAuditTable() {
        tableIns = febs.table.init({
            elem: $view.find("#surveyAuditRecord"),
            id: 'surveyAuditRecord',
            page:false,
            skin: '',
            limit:Number.MAX_VALUE,
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'auditRealName', title: '审核人姓名', width: 150},
                {field: 'auditResult',align:'center', title: '审核结果', width: 100, templet: function (d) {
                        return d.auditResult =='1'?'审核通过':'审核退回';
                    }
                },
                {field: 'auditReason', title: '审核理由', minWidth: 260},
                {field: 'createdTime',align:'center', title: '审核时间', width: 180},
            ]],
            done: function(res, curr, count){
            },
            data:surveyAuditRecordList
        });
    }

    $('#inputAutoLeader').autocomplete({
        serviceUrl: ctx + 'common/user/list',//测试接口
        paramName:'keywords',
        useType:'user',
        params:{ tenantId: tenantId},
        onSelect: function(suggestion) {
            setLeaderUserAndDeptAttr(suggestion);
        },
    });

    //事故原因分析图
    var fileUploadReportAnalysisDiv = fileUpload.render({
        elem: '#fileUploadReportAnalysis',
        url: ctx + 'accident/upload',
        type: 0,//0-图片，1-视频，2-其他
        maxNum:5,
        defaultData: getFileList_reportFx(),
        done: function (res) {
        },
    });
    function getFileList_reportFx() {
        if (accidentReportData.reportAnalysisFileList && accidentReportData.reportAnalysisFileList.length>0) {
            return  accidentReportData.reportAnalysisFileList;
        }else {
            return  [];
        }
    }

    //事故图解
    var fileUploadReportImgDiv = fileUpload.render({
        elem: '#fileUploadReportImg',
        url: ctx + 'accident/upload',
        type: 0,//0-图片，1-视频，2-其他
        maxNum:5,
        defaultData: getReportImgFileList(),
        done: function (res) {
        },
    });
    function getReportImgFileList() {
        if (accidentReportData.reportImgFileList && accidentReportData.reportImgFileList.length>0) {
            return  accidentReportData.reportImgFileList;
        }else {
            return  [];
        }
    }


    //事故调查附件
    fileUpload.render({
        elem:'#uploadBtn',
        url:ctx + 'accident/upload',
        type:'2',
        maxNum:5,
        defaultData: accidentReportData && accidentReportData.accidentSurveyFileList ? accidentReportData.accidentSurveyFileList:[],
        done:function(res){
        }
        ,error: function(){
            layer.msg("服务器异常")
        }
    })

    function resetRectifyInfo(selectData){
        $("#rectificationUserSelect").val('');
        $("#rectificationDeadline").val('');
        $("#rectificationOpinion").val('');
    }

    //增加整改措施信息
    $addOpinion.on('click', function () {
        var groupPanel = '<div class="layui-panel" id="panel_reason' + panelAddReason + '">' +
            '                                                <div class="layui-field-box">' +
            '                                                   <div class="layui-form-item febs-hide">' +
            '                                                        <label class="layui-form-label">：accident_report_reason id</label>' +
            '                                                        <div class="layui-input-block">' +
            '                                                            <input type="text" name="reportRectificationId" id="reportRectificationId' + panelAddReason + '" class="layui-input">' +
            '                                                        </div>' +
            '                                                    </div>' +
                                    '                           <div class="layui-form-item">' +
                                    '                               <div class="layui-row layui-row-button">' +
                                    '                                   <div name="delete" class="layui-btn layui-btn-danger layui-btn-sm">' +
                                    '                                       <em class="layui-icon layui-icon-delete"></em> 删除信息' +
                                    '                                   </div>' +
                                    '                               </div>' +
                                    '                           </div>' +
            '' +
            '                                                    <div class="layui-form-item">' +
            '                                                        <div class="layui-row">' +
            '                                                                <div class="layui-col-xs6">' +
            '                                                                    <label class="layui-form-label febs-form-item-require">整改责任人：</label>' +
            '                                                                    <div class="layui-input-block" style="position: relative">' +
                                                                                    '<div class="febs-hide">' +
                    '                                                                    <input type="text" name="obligationUserId" id="obligationUserId' + panelAddReason + '" >' +
                    '                                                                    <input type="text" name="obligationUserNo" id="obligationUserNo' + panelAddReason + '" >' +
                    '                                                                    <input type="text" name="obligationRealName" id="obligationRealName' + panelAddReason + '" >' +
                    '                                                                    <input type="text" name="obligationDeptId" id="obligationDeptId' + panelAddReason + '" >' +
                    '                                                                    <input type="text" name="obligationDeptName" id="obligationDeptName' + panelAddReason + '" >' +
                    '                                                                    <input type="text" name="obligationPostId" id="obligationPostId' + panelAddReason + '" >' +
                    '                                                                    <input type="text" name="obligationPostName" id="obligationPostName' + panelAddReason + '" >' +
                                                                                    '</div>'+
            '                                                                        <input type="text" id="rectificationUsers' + panelAddReason + '" name="rectificationUsers" autocomplete="off" class="layui-input"' +
            '                                                                               minlength="2" maxlength="50" placeholder="请选择整改人" lay-verify="required" >' +
            '                                                                        <div class="layui-input-suffix addUserBtn" id="rectificationUserSelect' + panelAddReason + '" name="rectificationUserSelect">' +
            '                                                                            <i class="layui-icon layui-icon-add-1"></i>' +
            '                                                                        </div>' +
            '                                                                    </div>' +
            '                                                                </div>' +
            '                                                                <div class="layui-col-xs6">' +
            '                                                                    <label class="layui-form-label febs-form-item-require">整改期限：</label>' +
            '                                                                    <div class="layui-input-block">' +
            '                                                                        <input type="text" name="rectificationDeadline" id="rectificationDeadline' + panelAddReason + '"' +
            '                                                                               placeholder="请输入期限时间" autocomplete="off" class="layui-input" lay-verify="required">' +
            '                                                                    </div>' +
            '                                                                </div>' +
            '                                                        </div>' +
            '                                                    </div>' +
            '                                                    <div class="layui-form-item" >' +
            '                                                        <div class="layui-row">' +
            '                                                            <div class="layui-col-xs12">' +
            '                                                                <label class="layui-form-label febs-form-item-require">整改措施：</label>' +
            '                                                                <div class="layui-input-block">' +
            '                                                                    <textarea type="text" name="rectificationOpinion" id="rectificationOpinion' + panelAddReason + '" autocomplete="off" class="layui-textarea" minlength="2"' +
            '                                                                              maxlength="800" placeholder="请输入整改措施" lay-verify="required"></textarea>' +
            '                                                                </div>' +
            '                                                            </div>' +
            '                                                        </div>' +
            '                                                    </div>' +
            '                                                </div>' +
            '                                            </div>';
        $("#reason_box").append(groupPanel);
        $("#rectificationUsers" + panelAddReason).autocomplete({
            serviceUrl: ctx + 'common/user/list',//测试接口
            paramName:'keywords',
            useType:'user',
            params:{ tenantId: tenantId},
            onSelect: function(suggestion) {
                var sort = this.getAttribute("id").slice(18);
                setRectificationUsers(suggestion,sort);
            },
        });
        laydate.render({
            elem: "#rectificationDeadline"+panelAddReason+"",
            done: function (value, date) {},
            type: 'date'
        });
        panelAddReason++;
        form.render();
    });


    $(document).off('click', 'div[name=delete]').on('click', 'div[name=delete]', function (e) {
        panelAddReason--;
        $(this).parents('div.layui-panel').remove();
        var reportRectificationId = $(this).parents('div.layui-panel').find('input[name="reportRectificationId"]').val();
        //删除的事故原因
        if(!commonJS.isEmpty(reportRectificationId)){
            deleteReportRectificationIds.push(reportRectificationId);
        }
        form.render();
    });

    // 监听时间轴的点击事件
    // $('.layui-timeline-axis').on('click', function(){
    //     // 在这里编写点击时间轴要执行的代码
    //     layer.msg('您点击了时间轴！');
    //     // 例如，新增一个时间线项
    //     var newItem = '<div class="layui-timeline-item">' +
    //         '            <i class="layui-icon layui-timeline-axis">&#xe63f;</i>' +
    //         '            <div class="layui-timeline-content layui-text">' +
    //         '              <h3 class="layui-timeline-title">新增的日期</h3>' +
    //         '              <p>新增的事件...</p>' +
    //         '            </div>' +
    //         '          </div>'
    //
    //     ;
    //     $('.layui-timeline').append(newItem);
    // });

    $addInjuryUser.on('click', function () {
        febs.modal.open('人员选择', 'common/user', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
            data:{
                tenantId:tenantId,
                selectList:injuryUserTableData,
                multiple:true,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                for (var i = 0; i < selectData.length; i++) {
                    var thisData = selectData[i];
                    var temp = setUserAttr(thisData);
                    injuryUserTableData.push(temp);
                }
                reloadInjuryTable(injuryUserTableData);
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });

    });

    function setUserAttr(thisData){
        var temp = {};
        temp.deptId = thisData.deptId;
        temp.deptName = thisData.deptName;
        temp.postId = thisData.postId;
        temp.postName = thisData.postName;
        temp.userId = thisData.userId;
        temp.identificationNo = thisData.identificationNo;
        temp.tenantId = thisData.tenantId;
        temp.userName = thisData.userName;
        temp.userNo = thisData.userNo;
        temp.realName = thisData.uname;
        temp.sex = thisData.sex;
        temp.userType = thisData.userType;
        temp.userDegree = thisData.literacy;
        temp.userSeniority = thisData.seniority;
        temp.contactsPhone = thisData.mobile;
        temp.joinDate = thisData.joinDate;
        return temp;
    }

    $addCulpritUser.on('click', function () {
        febs.modal.open('人员选择', 'common/user', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
            data:{
                tenantId:tenantId,
                selectList:culpritUserTableData,
                multiple:true,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                for (var i = 0; i < selectData.length; i++) {
                    var thisData = selectData[i];
                    var temp = setUserAttr(thisData);
                    culpritUserTableData.push(temp);
                }
                reloadCulpritTable(culpritUserTableData);
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });

    });

    //清空伤亡人员列表
    $view.find('#clearInjuryUser').on('click', function () {
        febs.modal.confirm('清空列表', '确定清空列表？', function (index) {
            injuryUserTableData = [];
            reloadInjuryTable(injuryUserTableData);
            layer.close(index);//关闭弹窗
        });
    });

    //清空肇事人员列表
    $view.find('#clearCulpritUser').on('click', function () {
        febs.modal.confirm('清空列表', '确定清空列表？', function (index) {
            culpritUserTableData = [];
            reloadCulpritTable(culpritUserTableData);
            layer.close(index);//关闭弹窗
        });
    });

    function initInjuryUserTable() {
        injuryUserTableIns = febs.table.init({
            elem: $view.find('#injuryUserTable'),
            id: 'injuryUserTable',
            page:false,
            skin: '',
            limit:Number.MAX_VALUE,
            editTrigger: 'dblclick',
            css: [ // 设置单元格样式
                // 取消默认的溢出隐藏，并设置适当高度
                '.layui-table-cell{height: 50px; line-height: 40px;}',
                '.layui-table-cell .layui-colorpicker{width: 38px; height: 38px;}',
                '.layui-table-cell select{height: 36px; padding: 0 5px;}'
            ].join(''),
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'userId', title: 'id',hide:true},
                {field: 'userName', title: 'userName',hide:true},
                {field: 'userNo', title: 'userNo',hide:true},
                {field: 'deptId', title: 'deptId',hide:true},
                {field: 'realName',align:'center', title: '姓名', width: 100},
                {field: 'workplace',align:'center', title: '工作单位', minWidth: 150,hide:true},
                {field: 'deptName',align:'center', title: '部门', minWidth: 150},
                {field: 'joinDate',align:'center', title: '入司时间', minWidth: 140},
                {field: 'userType',align:'center', title: '用工形式', width: 100, templet: function (d) {
                        var flg = '';
                        switch (d.userType) {
                            case "1": {
                                flg = '<span>本工</span>'
                                break;
                            }
                            case "2": {
                                flg = '<span>外包工</span>'
                                break;
                            }
                            case "3": {
                                flg = '<span>外协工</span>'
                                break;
                            }
                        }
                        return flg;
                    }
                },
                {field: 'userSeniority',align:'center', title: '工龄(年)<i class="layui-icon layui-icon-edit"></i>', width: 100,edit:'text',hide:true},
                {field: 'currentSeniority',align:'center', title: '本工种工龄<i class="layui-icon layui-icon-edit"></i>', width: 120,edit:'text'},
                {field: 'userDegree',align:'center', title: '学历<i class="layui-icon layui-icon-edit" title="双击单元格可编辑字段信息"></i>', width: 60,edit: 'text',hide:true},
                {field: 'identificationNo',align:'center', title: '<em class=" febs-form-item-require"></em>身份证号<i class="layui-icon layui-icon-edit" title="双击单元格可编辑字段信息"></i>', width: 170,edit: 'text'},
                {field: 'injuryPlace',align:'center', title: '受伤部位<i class="layui-icon layui-icon-edit"></i>', minWidth: 140,edit:'text'},
                {field: 'injuryLevel',align:'center',title: '<em class=" febs-form-item-require"></em>伤害程度',templet:'#injury-level', minWidth: 150},
                {field: 'lossHours',align:'center', title: '损失工时<i class="layui-icon layui-icon-edit" title="双击单元格可编辑字段信息"></i>', minWidth: 130,edit: 'text'},
                // {field: 'economyLoss',align:'center', title: '<em class=" febs-form-item-require"></em>经济损失(元)<i class="layui-icon layui-icon-edit" title="双击单元格可编辑字段信息"></i>', minWidth: 130,edit: 'text'},
                {title: '操作',align:'center', toolbar: '#injury-user-option', width: 50}
            ]],
            done: function(res, curr, count){
                var options = this;
                $view.find('.layui-table-body, .layui-table-box, .layui-table-cell').css('overflow', 'visible')
                var allCol= $view.find('#injuryUserTable .layui-table-body, .layui-table-box tbody .layui-table-cell')
                for(var i=0;i<allCol.length;i++){
                    var isSelect = $(allCol[i]).find("select[name='injuryLevel']")
                    if(isSelect.length==0){
                        $(allCol[i]).css('overflow', 'hidden')
                    }
                }
                // 获取当前行数据 - 自定义方法
                table.getRowData = function(tableId, elem){
                    var index = $(elem).closest('tr').data('index');
                    return table.cache[tableId][index] || {};
                };

                // layui table select 事件
                form.on('select(injuryLevel)', function(obj){
                    // 获取选中项 value
                    var userType = obj.value;
                    // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
                    var data = table.getRowData(options.id, obj.elem);
                    //修改对应数据的伤害等级
                    changeInjuryType(data.userId,userType);
                    //修改人员伤亡人数统计
                    changeInjuryCount(injuryUserTableData);
                });
                form.render();
            },
            data:injuryUserTableData
        });
    }

    function initCulpritUserTable() {
        culpritUserTableIns = febs.table.init({
            elem: $view.find('#culpritUserTable'),
            id: 'culpritUserTable',
            page:false,
            skin: '',
            limit:Number.MAX_VALUE,
            editTrigger: 'dblclick',
            css: [ // 设置单元格样式
                // 取消默认的溢出隐藏，并设置适当高度
                '.layui-table-cell{height: 50px; line-height: 40px;}',
                '.layui-table-cell .layui-colorpicker{width: 38px; height: 38px;}',
                '.layui-table-cell select{height: 36px; padding: 0 5px;}'
            ].join(''),
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'userId', title: 'id',hide:true},
                {field: 'userName', title: 'userName',hide:true},
                {field: 'userNo', title: 'userNo',hide:true},
                {field: 'deptId', title: 'deptId',hide:true},
                {field: 'realName',align:'center', title: '姓名', width: 140},
                {field: 'workplace',align:'center', title: '工作单位', minWidth: 150,hide:true},
                {field: 'deptName',align:'center', title: '部门', minWidth: 150},
                {field: 'joinDate',align:'center', title: '入司时间', minWidth: 140},
                {field: 'userType',align:'center', title: '用工形式', width: 100, templet: function (d) {
                        var flg = '';
                        switch (d.userType) {
                            case "1": {
                                flg = '<span>本工</span>'
                                break;
                            }
                            case "2": {
                                flg = '<span>外包工</span>'
                                break;
                            }
                            case "3": {
                                flg = '<span>外协工</span>'
                                break;
                            }
                        }
                        return flg;
                    }
                },
                {field: 'userSeniority',align:'center', title: '工龄(年)<i class="layui-icon layui-icon-edit"></i>', width: 120,edit:'text',hide:true},
                {field: 'currentSeniority',align:'center', title: '本工种工龄<i class="layui-icon layui-icon-edit"></i>', width: 120,edit:'text'},
                {field: 'userDegree',align:'center', title: '学历<i class="layui-icon layui-icon-edit" title="双击单元格可编辑字段信息"></i>', width: 100,edit: 'text'},
                {field: 'identificationNo',align:'center', title: '<em class=" febs-form-item-require"></em>身份证号<i class="layui-icon layui-icon-edit" title="双击单元格可编辑字段信息"></i>', width: 170,edit: 'text'},
                {field: 'lossHours',align:'center', title: '损失工时<i class="layui-icon layui-icon-edit" title="双击单元格可编辑字段信息"></i>', minWidth: 130,edit: 'text'},
                {title: '操作',align:'center', toolbar: '#culprit-user-option', width: 50}
            ]],
            done: function(res, curr, count){
            },
            data:culpritUserTableData
        });
    }

    function initTimelineTable() {
        timelineTableIns = febs.table.init({
            elem: $view.find('#timelineTable'),
            id: 'timelineTable',
            page:false,
            skin: '',
            limit:Number.MAX_VALUE,
            editTrigger: 'dblclick',
            css: [ // 设置单元格样式
                // 取消默认的溢出隐藏，并设置适当高度
                '.layui-table-cell{height: 50px; line-height: 40px;}',
                '.layui-table-cell .layui-colorpicker{width: 38px; height: 38px;}',
                '.layui-table-cell select{height: 36px; padding: 0 5px;}'
            ].join(''),
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'id',align:'center',title: 'id', hide:true},
                {field: 'accidentTime',align:'center',title: '<em class=" febs-form-item-require"></em>时间',templet:'#accident-time', width: 180},
                {field: 'accidentContent', title: '描述<i class="layui-icon layui-icon-edit"></i>', minWidth: 500,edit:'text'},
                {title: '操作',align:'center', toolbar: '#accident-time-option', width: 50}
            ]],
            done: function(res, curr, count){
                var options = this;
                $view.find('.layui-table-body, .layui-table-box, .layui-table-cell').css('overflow', 'visible')
                // 获取当前行数据 - 自定义方法
                table.getRowData_timeline = function(tableId, elem){
                    var index = $(elem).closest('tr').data('index');
                    return table.cache[tableId][index] || {};
                };
                laydate.render({
                    elem: ".accidentTimeClass",
                    done: function (value, date) {
                        var index = $(this.elem).parents('tr').attr('data-index');
                        var data = table.cache[options.id][index] || {};
                        data.accidentTime = value;
                        timelineTableData = layui.table.cache['timelineTable'];
                    },
                    type: 'datetime'
                })
                form.render();
            },
            data:timelineTableData
        });
    }

    table.on('tool(timelineTable)', function (obj) {
        var data = obj.data,
            that = this,
            tr = obj.tr,
            layEvent = obj.event;
        if (layEvent === 'del-accident-time') {
            febs.modal.confirm('删除', '确定删除？', function (index) {
                var cacheData = layui.table.cache['timelineTable'];//获取缓存
                obj.del();//①移除这一行
                var rowIndex = obj.tr.attr("data-index"); //获取行索引
                cacheData.splice(rowIndex, 1);  //②彻底移除元素，从缓存里移除这一行
                timelineTableData = cacheData;
                reloadTimelineTable(timelineTableData);
                layer.close(index);//关闭弹窗
            });
        }
    });

    $addTimeline.on('click', function () {
        var temp = {};
        temp.accidentTime = '';
        temp.accidentContent = '';
        timelineTableData.push(temp);
        reloadTimelineTable(timelineTableData);
        form.render();
    });

    //修改人员伤亡人数统计
    function changeInjuryCount(tableData){
        var deathToll = 0;
        var severeInjuryToll = 0;
        var slightInjuryToll = 0;
        var missingToll = 0;
        for (var i = 0; i < tableData.length; i++) {
            switch (tableData[i]['injuryLevel']) {
                case "1": {
                    slightInjuryToll++;
                    break;
                }
                case "2": {
                    severeInjuryToll++;
                    break;
                }
                case "3": {
                    deathToll++;
                    break;
                }
                case "4": {
                    missingToll++;
                    break;
                }
            }
        }
        $view.find("input[name=deathToll]").val(deathToll);
        $view.find("#deathTollSpan").text(deathToll);
        $view.find("input[name=severeInjuryToll]").val(severeInjuryToll);
        $view.find("#severeInjuryTollSpan").text(severeInjuryToll);
        $view.find("input[name=slightInjuryToll]").val(slightInjuryToll);
        $view.find("#slightInjuryTollSpan").text(slightInjuryToll);
        $view.find("input[name=missingToll]").val(missingToll);
        $view.find("#missingTollSpan").text(missingToll);
    }

    //修改对应数据的伤害等级
    function changeInjuryType(userId,selectVal){
        for (var i = 0; i < injuryUserTableData.length; i++) {
            if (injuryUserTableData[i]['userId'] === userId) {
                injuryUserTableData[i]['injuryLevel'] = selectVal;
            }
        }
    }

    table.on('edit(injuryUserTable)', function (obj) {
      var value = obj.value;//值
      var field = obj.field;//字段
        if(field == 'economyLoss'){
            if(commonJS.isEmpty(value)){
                return febs.alert.warn('请输入经济损失');
            }
            if(!commonJS.amountVerify(value)){
                obj.data.economyLoss='';
                obj.update(obj.data);
                injuryUserTableIns.reload(1);
                return febs.alert.warn('请输入正确的金额格式，例如：100.00');
            }
        }
        if(field == 'lossHours'){
            if(!/^[0-9]+$/.test(value)){
                obj.data.lossHours='';
                obj.update(obj.data);
                injuryUserTableIns.reload(1);
                return febs.alert.warn('输入内容必须是正整数');
            }
        }
        if(field == 'currentSeniority'){
            if(!/^[0-9]+$/.test(value)){
                obj.data.currentSeniority='';
                obj.update(obj.data);
                injuryUserTableIns.reload(1);
                return febs.alert.warn('输入内容必须是正整数');
            }
        }

        if(field == 'userSeniority'){
            if(!/^[0-9]+$/.test(value)){
                obj.data.userSeniority='';
                obj.update(obj.data);
                injuryUserTableIns.reload(1);
                return febs.alert.warn('输入内容必须是正整数');
            }
        }
        if(field == 'identificationNo'){
            if(!commonJS.identificationNoVerify(value)){
                obj.data.identificationNo='';
                obj.update(obj.data);
                injuryUserTableIns.reload(1);
                return febs.alert.warn('身份证号格式不正确');
            }
        }
    });

    table.on('edit(culpritUserTable)', function (obj) {
      var value = obj.value;//值
      var field = obj.field;//字段
        if(field == 'userSeniority'){
            if(!/^[0-9]+$/.test(value)){
                obj.data.userSeniority='';
                obj.update(obj.data);
                culpritUserTableIns.reload(1);
                return febs.alert.warn('输入内容必须是正整数');
            }
        }
        if(field == 'lossHours'){
            if(!/^[0-9]+$/.test(value)){
                obj.data.lossHours='';
                obj.update(obj.data);
                culpritUserTableIns.reload(1);
                return febs.alert.warn('输入内容必须是正整数');
            }
        }
        if(field == 'currentSeniority'){
            if(!/^[0-9]+$/.test(value)){
                obj.data.currentSeniority='';
                obj.update(obj.data);
                culpritUserTableIns.reload(1);
                return febs.alert.warn('输入内容必须是正整数');
            }
        }
        if(field == 'identificationNo'){
            if(!commonJS.identificationNoVerify(value)){
                obj.data.identificationNo='';
                obj.update(obj.data);
                injuryUserTableIns.reload(1);
                return febs.alert.warn('身份证号格式不正确');
            }
        }
    });

    table.on('tool(injuryUserTable)', function (obj) {
        var data = obj.data,
            that = this,
            tr = obj.tr,
            layEvent = obj.event;
        if (layEvent === 'del-injury-user') {
            febs.modal.confirm('删除', '确定删除？', function (index) {
                var cacheData = layui.table.cache['injuryUserTable'];//获取缓存
                obj.del();//①移除这一行
                var rowIndex = obj.tr.attr("data-index"); //获取行索引
                cacheData.splice(rowIndex, 1);  //②彻底移除元素，从缓存里移除这一行
                injuryUserTableData = cacheData;
                reloadInjuryTable(injuryUserTableData);
                layer.close(index);//关闭弹窗
            });
        }
    });

    table.on('tool(culpritUserTable)', function (obj) {
        var data = obj.data,
            that = this,
            tr = obj.tr,
            layEvent = obj.event;
        if (layEvent === 'del-culprit-user') {
            febs.modal.confirm('删除', '确定删除？', function (index) {
                var cacheData = layui.table.cache['culpritUserTable'];//获取缓存
                obj.del();//①移除这一行
                var rowIndex = obj.tr.attr("data-index"); //获取行索引
                cacheData.splice(rowIndex, 1);  //②彻底移除元素，从缓存里移除这一行
                culpritUserTableData = cacheData;
                reloadCulpritTable(culpritUserTableData);
                layer.close(index);//关闭弹窗
            });
        }
    });




    function reloadInjuryTable(data){
        injuryUserTableIns.reload({data:data});
    }

    function reloadCulpritTable(data){
        culpritUserTableIns.reload({data:data});
    }

    function reloadTimelineTable(data){
        timelineTableIns.reloadData({data:data});
    }

    form.on('switch(rectificationFlg)', function(data){
        var index = this.getAttribute('id').slice(16);
        var status = data.elem.checked;
        if(!status){
            //无需整改
            $view.find('div[name=ifShow'+index+']').addClass('febs-hide');
            $view.find('#rectificationDeadline'+index).attr("lay-verify","");
            $view.find('#rectificationDeadline'+index).val("");
            $view.find('#rectificationDeadline-label'+index).removeClass("febs-form-item-require");
            $view.find('#reasonContent'+index).attr("lay-verify","");
            $view.find('#reasonContent'+index).val("");
            $view.find('#reasonContent-label'+index).removeClass("febs-form-item-require");
            $view.find('#rectificationOpinion'+index).attr("lay-verify","");
            $view.find('#rectificationOpinion'+index).val("");
            $view.find('#rectificationOpinion-label'+index).removeClass("febs-form-item-require");
            $view.find('#rectificationUsers'+index).attr("lay-verify","");
            $view.find('#rectificationUsers'+index).val("");
            $view.find('#rectificationUsers-label'+index).removeClass("febs-form-item-require");
        }else{
            //待整改
            $view.find('div[name=ifShow'+index+']').removeClass('febs-hide');
            $view.find('#rectificationDeadline'+index).attr("lay-verify","required");
            $view.find('#rectificationDeadline-label'+index).addClass("febs-form-item-require");
            $view.find('#rectificationOpinion'+index).attr("lay-verify","required");
            $view.find('#rectificationOpinion-label'+index).addClass("febs-form-item-require");
            $view.find('#reasonContent'+index).attr("lay-verify","required");
            $view.find('#reasonContent-label'+index).addClass("febs-form-item-require");
            $view.find('#rectificationUsers'+index).attr("lay-verify","required");
            $view.find('#rectificationUsers-label'+index).addClass("febs-form-item-require");
        }
    });

    $view.find('#reason_box').on('click', '.addUserBtn',function (e) {
        var sort = this.getAttribute("id").slice(23);
        febs.modal.open('整改人选择', 'common/user', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
            data:{
                tenantId:tenantId,
                multiple:false,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                setRectificationUsers(selectData,sort);
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });
    });

    function setRectificationUsers(userData,sort){
        if (userData) {
            $("#rectificationUsers"+sort).val(userData.uname+'('+userData.userNo+'|'+userData.deptName+')');
            $("#obligationUserId"+sort).val(userData.userId);
            $("#obligationUserNo"+sort).val(userData.userNo);
            $("#obligationRealName"+sort).val(userData.uname);
            $("#obligationDeptId"+sort).val(userData.deptId);
            $("#obligationDeptName"+sort).val(userData.deptName);
            $("#obligationPostId"+sort).val(userData.postId);
            $("#obligationPostName"+sort).val(userData.postName);
        }
    }

    $obligationDeptName.on('click', function () {
        febs.modal.open('责任部门及责任人选择', 'common/user', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
            data:{
                tenantId:tenantId,
                multiple:false,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                setLeaderUserAndDeptAttr(selectData);
                $("#showLeaderUserInfo").show();
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });
    });

    function initDictItemSelect_surveyRecord(){
        //事故类别
        febs.initDictItemSelect($accidentCategory,'SAFETY_ACCIDENT_CATEGORY',accidentReportData.accidentCategory,null);
        //事故类型
        febs.initDictItemSelect($accidentType,'SAFETY_ACCIDENT_TYPE',accidentReportData.accidentType,null);

        //事故等级
        febs.initDictItemSelect($accidentLevel,'SAFETY_ACCIDENT_LEVEL',accidentReportData.accidentLevel,null);
        //事故性质
        febs.initDictItemSelect($accidentNature,'SAFETY_ACCIDENT_NATURE',accidentReportData.accidentNature,null);

        //违反保命规则
        febs.initDictItemSelect($violationSurvivalRules,'SAFETY_ACCIDENT_VIOLATION_SURVIVAL_RULES',accidentReportData.violationSurvivalRules,null);

        //原因分类
        febs.initDictItemSelect($accidentReason,'SAFETY_ACCIDENT_REASON',accidentReportData.accidentReason,null);

        //应急反应级别
        febs.initDictItemSelect($emergencyLevel,'SAFETY_ACCIDENT_EMERGENCY_LEVEL',accidentReportData.emergencyLevel,null);
        //直接原因
        febs.initDictItemSelect($directReason,'SAFETY_ACCIDENT_DIRECT_REASON',accidentReportData.directReason,null);

        //间接原因
        febs.initDictItemSelect($indirectionReason,'SAFETY_ACCIDENT_INDIRECTION_REASON',accidentReportData.indirectionReason,null);

        //根本原因
        febs.initDictItemSelect($rootReason,'SAFETY_ACCIDENT_ROOT_REASON',accidentReportData.rootReason,null);

    }
    function setLeaderUserAndDeptAttr(selectData){
        $view.find("input[name=obligationDeptId]").val(selectData.deptId);
        $view.find("input[name=obligationDeptName]").val(selectData.deptName);
        $view.find("#obligationDeptNameDiv").text(selectData.deptName);
        $view.find("input[name=obligationUserId]").val(selectData.userId);
        $view.find("input[name=obligationUserName]").val(selectData.userName);
        $view.find("input[name=obligationRealName]").val(selectData.uname);
        $view.find("input[name=obligationUserNo]").val(selectData.userNo);
        $view.find("#obligationUserNoDiv").text(selectData.userNo);
        $view.find("input[name=obligationPostId]").val(selectData.postId);
        $view.find("input[name=obligationPostName]").val(selectData.postName);
        $view.find("#obligationPostNameDiv").text(selectData.postName==null?'':selectData.postName);
    }

    function initProjectAreaId(projectId) {
        if(projectId){
            //初始化项目区域
            var data ={
                tenantId:POPUP_DATA.tenantId,
                projectId:projectId
            };
            $("#accidentAreaId").empty();
            febs.getSync(ctx + 'baseProjectArea', data, function (r) {
                var resultData = r.data;
                var options = '<option value="">请选择</option>';
                $.each(resultData, function (index, item) {
                    options += '<option value="' + item.areaId + '">' + item.areaName + '</option>'
                })
                $("#accidentAreaId").append(options);
            });
        }

    }

    form.on('select(projectId)', function(obj){
        // 获取选中项 value
        var projectId = obj.value;
        var selectProject = $view.find("select[name='projectId']").find("option:selected");
        if(projectId == ''){
            $("#accidentAreaId").empty();
            $view.find('input[name="projectName"]').val("");
        }else {
            initProjectAreaId(projectId);
            $view.find('input[name="projectName"]').val(selectProject.text());
        }
        form.render();
    });

    form.on('select(accidentAreaId)', function(obj){
        var accidentAreaId = obj.value;
        // 获取选中项 value
        var accidentAreaName = $view.find("select[name='accidentAreaId']").find("option:selected").text();
        if(accidentAreaId == ''){
            $view.find('input[name="accidentAreaName"]').val("");
        }else {
            $view.find('input[name="accidentAreaName"]').val(accidentAreaName);
        }
        form.render();
    });
    function initFormValue() {
        if (accidentReportData) {
            //伤亡人员
            injuryUserTableData = accidentReportData.injuryUserDataList;
            //肇事人员
            culpritUserTableData = accidentReportData.culpritUserDataList;
            //时间线
            timelineTableData = accidentReportData.timelineList;
            //整改审核记录
            if(accidentReportData.surveyAuditRecordList && accidentReportData.surveyAuditRecordList.length>0){
                surveyAuditRecordList = accidentReportData.surveyAuditRecordList;
            }
            initProjectAreaId(accidentReportData.projectId);
            form.val("reportSurveyRecord-edit-form", {
                "reportId": accidentReportData.reportId,
                "tenantId": accidentReportData.tenantId,
                "accidentNo": accidentReportData.accidentNo,
                "accidentTitle": accidentReportData.accidentTitle,
                "accidentDate": accidentReportData.accidentDate,
                "accidentPlace": accidentReportData.accidentPlace,
                "accidentType": accidentReportData.accidentType,
                "accidentLevel": accidentReportData.accidentLevel,
                "accidentShipType": accidentReportData.accidentShipType,
                "preliminarilyDamage": accidentReportData.preliminarilyDamage,
                "preliminarilyDescript": accidentReportData.preliminarilyDescript,
                "acceptAssistFlg": accidentReportData.acceptAssistFlg,
                "surveyStatus": accidentReportData.surveyStatus,
                "surveyDeadline": accidentReportData.surveyDeadline,
                "surveyRemark": accidentReportData.surveyRemark,
                "projectId": accidentReportData.projectId,
                "projectName": accidentReportData.projectName,
                "accidentAreaId": accidentReportData.accidentAreaId,
                "accidentAreaName": accidentReportData.accidentAreaName,
                "noticeDeptFlg": accidentReportData.noticeDeptFlg,
                "noticeDeptName": accidentReportData.noticeDeptName,
                "noticeDeptDate": accidentReportData.noticeDeptDate,
                "accidentOverview": accidentReportData.accidentOverview,
                "accidentCategory": accidentReportData.accidentCategory,
                "detailPlace": accidentReportData.detailPlace,
                "accidentNature": accidentReportData.accidentNature,
                "violationSurvivalRules": accidentReportData.violationSurvivalRules,
                "accidentElapse": accidentReportData.accidentElapse,
                "emergencyOverview": accidentReportData.emergencyOverview,
                "emergencyLevel": accidentReportData.emergencyLevel,
                "totalLossHours": accidentReportData.totalLossHours,
                "environmentEffect": accidentReportData.environmentEffect,
                "totalLoss": accidentReportData.totalLoss,
                "economyLoss": accidentReportData.economyLoss,
                "indirectLoss": accidentReportData.indirectLoss,
                "accidentReason": accidentReportData.accidentReason,
                "directReason": accidentReportData.directReason,
                "directReasonRemark": accidentReportData.directReasonRemark,
                "indirectionReason": accidentReportData.indirectionReason,
                "indirectionReasonRemark": accidentReportData.indirectionReasonRemark,
                "rootReason": accidentReportData.rootReason,
                "rootReasonRemark": accidentReportData.rootReasonRemark,
                "accidentAnalysis": accidentReportData.accidentAnalysis,
                "obligationUserId": accidentReportData.obligationUserId,
                "obligationUserNo": accidentReportData.obligationUserNo,
                "obligationRealName": accidentReportData.obligationRealName,
                "obligationDeptId": accidentReportData.obligationDeptId,
                "obligationDeptName": accidentReportData.obligationDeptName,
                "obligationPostId": accidentReportData.obligationPostId,
                "obligationPostName": accidentReportData.obligationPostName,
                "obligationRatio": accidentReportData.obligationRatio,
                "obligationCognizance": accidentReportData.obligationCognizance,
                "obligationDisposeCondition": accidentReportData.obligationDisposeCondition,
                "status": accidentReportData.status,
                "deathToll": accidentReportData.deathToll,
                "severeInjuryToll": accidentReportData.severeInjuryToll,
                "slightInjuryToll": accidentReportData.slightInjuryToll,
                "missingToll": accidentReportData.missingToll,
                "noticeChic": accidentReportData.noticeChic,
                "noticeDate": accidentReportData.noticeDate,
                "surveyAuditUserId": accidentReportData.surveyAuditUserId,
                "surveyAuditRealName": accidentReportData.surveyAuditRealName,
                "surveyAuditDate": accidentReportData.surveyAuditDate,
                "surveyAuditRemark": accidentReportData.surveyAuditRemark,
                "cautionaryFlg": accidentReportData.cautionaryFlg,
                "workflowApplyId": accidentReportData.workflowApplyId,
                "reportAnalysisFileList": accidentReportData.reportAnalysisFileList,
                "reportImgFileList": accidentReportData.reportImgFileList,
                "surveyAuditRecordList": accidentReportData.surveyAuditRecordList,
                "rectificationOpinionList": accidentReportData.rectificationOpinionList,
            });

            if (accidentReportData.obligationUserId) {
                $view.find("#obligationDeptNameDiv").text(accidentReportData.obligationDeptName);
                $view.find("#obligationUserNoDiv").text(accidentReportData.obligationUserNo);
                $view.find("#obligationPostNameDiv").text(accidentReportData.obligationPostName);
            }

            if (accidentReportData.rectificationOpinionList && accidentReportData.rectificationOpinionList.length>0) {
                //添加原因的序号从已有的length开始
                let reasonList = accidentReportData.rectificationOpinionList;
                panelAddReason = reasonList.length;
                if(reasonList.length > 0){
                    for(let i=0;i<reasonList.length;i++){
                        appendHtml(i,reasonList[i]);
                    }
                }
            }
            form.render('checkbox');
        }
        //给页面原因列表渲染
        if (accidentReportData.rectificationOpinionList){
            setPanelInfo(accidentReportData.rectificationOpinionList);
        }
        //人员伤亡统计
        $view.find("#deathTollSpan").text(accidentReportData.deathToll==null?'':accidentReportData.deathToll);
        $view.find("#severeInjuryTollSpan").text(accidentReportData.severeInjuryToll==null?'':accidentReportData.severeInjuryToll);
        $view.find("#slightInjuryTollSpan").text(accidentReportData.slightInjuryToll==null?'':accidentReportData.slightInjuryToll);
        $view.find("#missingTollSpan").text(accidentReportData.missingToll==null?'':accidentReportData.missingToll);
    }

    function setPanelInfo(dataList){
        for(let n=0;n<dataList.length;n++){
            var item = dataList[n];
            var elemet = $(".layui-panel").eq(n);

            //整改措施
            elemet.find('input[name="rectificationUsers"]').val(item.obligationRealName+'('+item.obligationUserNo+'|'+item.obligationDeptName+')');
            elemet.find('input[name="reportRectificationId"]').val(item.reportRectificationId);
            elemet.find('input[name="obligationUserId"]').val(item.obligationUserId);
            elemet.find('input[name="obligationUserNo"]').val(item.obligationUserNo);
            elemet.find('input[name="obligationRealName"]').val(item.obligationRealName);
            elemet.find('input[name="obligationDeptId"]').val(item.obligationDeptId);
            elemet.find('input[name="obligationDeptName"]').val(item.obligationDeptName);
            elemet.find('input[name="obligationPostId"]').val(item.obligationPostId);
            elemet.find('input[name="obligationPostName"]').val(item.obligationPostName);
            elemet.find('input[name="rectificationDeadline"]').val(item.rectificationDeadline);
            elemet.find('textarea[name="rectificationOpinion"]').val(item.rectificationOpinion);
        }
        form.render();
    }

    function appendHtml(sort,item){
        var groupPanelAppend = '<div class="layui-panel" id="panel_reason' + sort + '">' +
            '                                                <div class="layui-field-box" name="reasonBox">' +
            '                                                   <div class="layui-form-item febs-hide">' +
            '                                                        <label class="layui-form-label">：accident_report_reason id</label>' +
            '                                                        <div class="layui-input-block">' +
            '                                                            <input type="text" name="reportRectificationId" id="reportRectificationId' + sort + '" class="layui-input">' +
            '                                                        </div>' +
            '                                                    </div>' +
                                    '                           <div class="layui-form-item">' +
                                    '                               <div class="layui-row layui-row-button">' +
                                    '                                   <div name="delete" class="layui-btn layui-btn-danger layui-btn-sm">' +
                                    '                                       <em class="layui-icon layui-icon-delete"></em> 删除信息' +
                                    '                                   </div>' +
                                    '                               </div>' +
                                    '                           </div>' +
            '' +
            '                                                    <div class="layui-form-item">' +
            '                                                        <div class="layui-row">' +
        '                                                                <div class="layui-col-xs6">' +
        '                                                                    <label class="layui-form-label febs-form-item-require" >整改责任人：</label>' +
        '                                                                    <div class="layui-input-block" style="position: relative">' +
                                                                                '<div class="febs-hide">' +
                '                                                                    <input type="text" name="obligationUserId" id="obligationUserId' + sort + '" >' +
                '                                                                    <input type="text" name="obligationUserNo" id="obligationUserNo' + sort + '" >' +
                '                                                                    <input type="text" name="obligationRealName" id="obligationRealName' + sort + '" >' +
                '                                                                    <input type="text" name="obligationDeptId" id="obligationDeptId' + sort + '" >' +
                '                                                                    <input type="text" name="obligationDeptName" id="obligationDeptName' + sort + '" >' +
                '                                                                    <input type="text" name="obligationPostId" id="obligationPostId' + sort + '" >' +
                '                                                                    <input type="text" name="obligationPostName" id="obligationPostName' + sort + '" >' +
                                                                                '</div>'+
        '                                                                        <input type="text" id="rectificationUsers' + sort + '" name="rectificationUsers" autocomplete="off" class="layui-input"' +
        '                                                                               minlength="2" maxlength="50"  lay-verify="required">' +
        '                                                                        <div class="layui-input-suffix addUserBtn" id="rectificationUserSelect' + sort + '" name="rectificationUserSelect">' +
        '                                                                            <i class="layui-icon layui-icon-add-1"></i>' +
        '                                                                        </div>' +
        '                                                                    </div>' +
        '                                                                </div>' +
        '                                                                <div class="layui-col-xs6">' +
        '                                                                    <label class="layui-form-label febs-form-item-require">整改期限：</label>' +
        '                                                                    <div class="layui-input-block">' +
        '                                                                        <input type="text" name="rectificationDeadline" id="rectificationDeadline' + sort + '"' +
        '                                                                               placeholder="请输入期限时间" autocomplete="off" class="layui-input" lay-verify="required">' +
        '                                                                    </div>' +
        '                                                                </div>' +
    '                                                                </div>' +
            '                                                    </div>' +
            '                                                    <div class="layui-form-item" >' +
            '                                                        <div class="layui-row">' +
            '                                                            <div class="layui-col-xs12">' +
            '                                                                <label class="layui-form-label febs-form-item-require">整改措施：</label>' +
            '                                                                <div class="layui-input-block">' +
            '                                                                    <textarea type="text" name="rectificationOpinion" id="rectificationOpinion' + sort + '" autocomplete="off" class="layui-textarea" minlength="2"' +
            '                                                                              maxlength="800" placeholder="请输入整改措施" lay-verify="required"></textarea>' +
            '                                                                </div>' +
            '                                                            </div>' +
            '                                                        </div>' +
            '                                                    </div>' +
            '                                                </div>' +
            '                                            </div>';
        $("#reason_box").append(groupPanelAppend);
        $("#rectificationUsers" + sort).autocomplete({
            serviceUrl: ctx + 'common/user/list',//测试接口
            paramName:'keywords',
            useType:'user',
            params:{ tenantId: tenantId},
            onSelect: function(suggestion) {
                var sort = this.getAttribute("id").slice(18);
                setRectificationUsers(suggestion,sort);
            },
        });
        laydate.render({
            elem: "#rectificationDeadline"+sort+"",
            done: function (value, date) {},
            type: 'date'
        });
        form.render();
    }


    //查看事故基本信息
    $view.find('#accidentInfoShow').on('click', function () {
        febs.modal.open('事故上报基本信息', 'accidentReport/accidentReportBaseInfo/'+accidentReportData.reportId, {
            btn: ['关闭'],
            area: $(window).width() <= 750 ?  ['85%', '80%']: ['95%', '95%'],
            shadeClose:true,
            yes: function (index, layero) {
                layer.close(index);
            },
        });
    });

    form.on('submit(reportSurveyRecord-edit-form-save)', function (data) {
        if(!checkValid(injuryUserTableData) || !checkValidTimeline(timelineTableData)) {
            return false;
        }
        // data.timelineList = timelineTableData;
        addOrUpdate(data.field,'保存');
        return false;
    });

    form.on('submit(reportSurveyRecord-edit-form-submit)', function (data) {
        //accident_report  survey_status(调查状态) 3：进行中
        data.field.surveyStatus = '3';
        if(!checkValid(injuryUserTableData)  || !checkValidTimeline(timelineTableData)) {
            return false;
        }
        addOrUpdate(data.field,'提交');
        return false;
    });

    function checkValid(data){
        var result = true;
        if(!commonJS.isEmpty(data)){
            try{
                data.some(item=> {
                    if(commonJS.isEmpty(item.identificationNo)){
                        febs.alert.warn('伤亡人员、肇事人员身份证号不能为空！');
                        result = false;
                        throw Error('伤亡人员、肇事人员身份证号不能为空！');
                    }
                    // if(commonJS.isEmpty(item.economyLoss)){
                    //     febs.alert.warn('伤亡人员经济损失不能为空！');
                    //     result = false;
                    //     throw Error('伤亡人员经济损失不能为空！');
                    // }
                    // if(!commonJS.amountVerify(item.economyLoss)){
                    //     febs.alert.warn('请输入正确的金额格式，例如：100.00');
                    //     result = false;
                    //     throw Error('请输入正确的金额格式，例如：100.00');
                    // }
                    // if(commonJS.isEmpty(item.lossHours)){
                    //     febs.alert.warn('伤亡人员损失工时不能为空！');
                    //     result = false;
                    //     throw Error('伤亡人员损失工时不能为空！');
                    // }
                    // if(!commonJS.amountVerify(item.lossHours)){
                    //     febs.alert.warn('请输入正确的工时格式，例如：8.00');
                    //     result = false;
                    //     throw Error('请输入正确的工时格式，例如：8.00');
                    // }
                })
            } catch (err){

            }
        }
        return result;
    }

    function checkValidTimeline(data){
        var result = true;
        if(!commonJS.isEmpty(data)){
            try{
                data.some(item=> {
                    if(commonJS.isEmpty(item.accidentTime)){
                        febs.alert.warn('时间线时间不能为空！');
                        result = false;
                        throw Error('时间线时间不能为空！');
                    }
                })
            } catch (err){

            }
        }
        return result;
    }
    function addOrUpdate(data,operation) {
        data.tenantId = tenantId;
        data.obligationPostName = $("#obligationPostName0").val();
        data.obligationPostId = $("#obligationPostId0").val();
        data.accidentAreaName = $("#accidentAreaId").find("option:selected").text().trim();
        data.projectName = $("#projectId").find("option:selected").text().trim();
        //页面删除的事故整改措施，传到后端，只删除这些id的数据，其他数据做更新处理
        data.deleteReportRectificationIds = deleteReportRectificationIds.join(',');
        data.injuryUserDataList = injuryUserTableData;
        data.culpritUserDataList = culpritUserTableData;
        data.timelineList = timelineTableData;
        data.accidentSurveyFileList = getAccidentSurveyFileList($("#uploadBtn"));
        data.reportAnalysisFileList = getImgData($("#fileUploadReportAnalysis"));
        data.reportImgFileList = getImgData($("#fileUploadReportImg"));

        //整改措施list
        data.rectificationOpinionList = saveRectificationOpinionList(operation);
        if(!data.rectificationOpinionList || data.rectificationOpinionList.length==0){
            febs.alert.warn('请录入整改措施!');
            return false ;
        }
        if (data.reportId && data.reportId.length > 0) {
            febs.modal.confirm(operation+'调查结果信息','确定'+operation+'调查结果信息？', function (index) {
                febs.postArray(ctx + 'accidentReport/surveyRecord', data, function () {
                    layer.closeAll();
                    febs.alert.success(operation+'成功');
                    $('#febs-accidentReportSurvey').find('#query').trigger('click');
                });
            });
        }
    }

    function getAccidentSurveyFileList(elem){
        var fileDatas = elem.find(".fileOne")
        var fileList = [];
        $.each(fileDatas,function (index, item){
            var data = {
                filePath: item.dataset.filepath,
                fileName: item.dataset.filename,
                smallPath: item.dataset.smallpath,
            }
            fileList.push(data);
        })
        return fileList;
    }

    function saveRectificationOpinionList(operation){
        var rectificationOpinionList = [];
        $(".layui-panel").each(function (index, item) {
            var elemet = $(".layui-panel").eq(index);
            //对于做了隐藏处理的整改措施，说明是已经调查录入提交过的，在新增调查录入时，这些数据不应该做改动
            if(!elemet.hasClass('febs-hide')){
                var reportRectificationId = elemet.find('input[name="reportRectificationId"]').val();
                var obligationUserId = elemet.find('input[name="obligationUserId"]').val();
                var obligationUserNo = elemet.find('input[name="obligationUserNo"]').val();
                var obligationRealName = elemet.find('input[name="obligationRealName"]').val();
                var obligationDeptId = elemet.find('input[name="obligationDeptId"]').val();
                var obligationDeptName = elemet.find('input[name="obligationDeptName"]').val();
                var obligationPostId = elemet.find('input[name="obligationPostId"]').val();
                var obligationPostName = elemet.find('input[name="obligationPostName"]').val();
                var rectificationDeadline = elemet.find('input[name="rectificationDeadline"]').val();
                var rectificationOpinion = elemet.find('textarea[name="rectificationOpinion"]').val();
                var rectificationStatus ='1';
                if(operation == '提交'){
                    rectificationStatus = '2';
                }
                rectificationOpinionList.push({
                    tenantId: tenantId,
                    reportId: reportId,
                    reportRectificationId: reportRectificationId,
                    obligationUserId: obligationUserId,
                    obligationUserNo: obligationUserNo,
                    obligationRealName: obligationRealName,
                    obligationDeptId: obligationDeptId,
                    obligationDeptName: obligationDeptName,
                    obligationPostId: obligationPostId,
                    obligationPostName: obligationPostName,
                    rectificationOpinion: rectificationOpinion,
                    rectificationDeadline: rectificationDeadline,
                    rectificationStatus: rectificationStatus,
                })
            }
        })
        return rectificationOpinionList;
    }

    function getImgData(elem){
        var imgDatas = elem.find(".imgOne")
        var imgList = [];
        $.each(imgDatas,function (index, item){
            var data = {
                filePath: item.dataset.filepath,
                fileName: item.dataset.filename,
                smallPath: item.dataset.smallpath,
            }
            imgList.push(data);
        })
        return imgList;
    }

});